package com.fs.controller;

import com.fs.controller.vo.customer.ReqCreateCustomer;
import com.fs.controller.vo.customer.RespCustomer;
import com.fs.controller.vo.user.ReqGetToken;
import com.fs.global.init.RoleName;
import com.fs.realm.JwtUtil;
import com.fs.service.CustomerService;
import com.fs.service.UserService;
import com.fs.service.bo.customer.BoCreateParam;
import com.fs.service.bo.customer.BoCustomer;
import com.fs.service.bo.user.BoRoleInfo;
import com.fs.service.bo.user.BoUserInfoWithRole;
import io.swagger.annotations.*;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.validation.annotation.*;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "登录", description = "获取api令牌")
@RestController
public class LoginController {

    private final UserService userService;
    private final CustomerService customerService;
    private final String WX_CUSTOMER_LOGIN_NAME = "customer";
    private final String WX_CUSTOMER_PASSWORD = "1q2w3e4r5t";

    public LoginController(UserService userService, CustomerService customerService) {
        this.userService = userService;
        this.customerService = customerService;
    }


    @ApiOperation("后台管理员或小程序访客获取token")
    @PostMapping("/user/token")
    public String getUserToken(@RequestBody @Validated ReqGetToken vo) {
        BoUserInfoWithRole userInfo = userService.getUserByLoginName(vo.getLoginName(), vo.getPassword());
        if (userInfo == null) {
            throw new UserNotFoundException();
        }
        List<String> roles = userInfo.getRoles().stream().map(BoRoleInfo::getName).collect(Collectors.toList());

        if (userInfo.getToken() != null) {
            if (JwtUtil.verify(userInfo.getToken())) {
                return userInfo.getToken();
            }
        }

        String token = JwtUtil.sign(userInfo.getId(), roles);
        userService.updateUserToken(token, userInfo.getId());
        return token;
    }

    @ApiOperation("小程序顾客获取token")
    @PostMapping("/customer/token")
    public String getCustomerToken(@RequestBody @Valid ReqCreateCustomer req) {
        if (!req.getUsername().equals(WX_CUSTOMER_LOGIN_NAME) || !req.getPassword().equals(WX_CUSTOMER_PASSWORD)) {
            throw new AuthenticationException();
        }

        BoCustomer customer = customerService.findByOpenIDNotThrow(req.getOpenId());

        if (customer == null) {
            BoCreateParam param = new BoCreateParam().setName(req.getNickName())
                    .setWxID(req.getOpenId()).setAvatarUrl(req.getAvatarUrl()).setPhone(req.getPhone());
            BoCustomer newCustomer = customerService.createCustomer(param);

            String token = JwtUtil.sign(newCustomer.getId(), Collections.singletonList(RoleName.CUSTOMER));
            customerService.updateToken(newCustomer.getId(), token);
            return token;

        } else {
            customerService.updateName(customer.getId(), req.getNickName(), req.getAvatarUrl());
            if (customer.getToken() != null && JwtUtil.verify(customer.getToken())) {
                return customer.getToken();

            } else {
                String token = JwtUtil.sign(customer.getId(), Collections.singletonList(RoleName.CUSTOMER));
                customerService.updateToken(customer.getId(), token);
                return token;
            }
        }
    }


}
